package com.ld.hpfs.web.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.ExtReturn;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.RuleService;
import com.ld.hpfs.web.interseptor.WebConstants;
import com.ld.hpfs.dao.UtilMapper;

@Controller
public class RuleController {
	private static final Logger logger = LoggerFactory
			.getLogger(RuleController.class);
	@Autowired
	private RuleService ruleservice;
	@Autowired
	private UtilMapper utilMapper;

	/*
	 * 判断当前客户是否已经存在返利和折扣规则
	 * 
	 * @Return: True:不存在；False:存在
	 */
	@RequestMapping(value = "/checkDiscountReturnRepeat")
	public void checkDiscountReturnRepeat(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();

		try {
			// 获取规则类型，有效范围，客户代码项目值
			String rule_type = (String) request.getParameter("ruleType") == null ? null
					: (String) request.getParameter("ruleType");
			String scopeFlag = (String) request.getParameter("scopeFlag") == null ? null
					: (String) request.getParameter("scopeFlag");
			String cust_code = (String) request.getParameter("custCode") == null ? null
					: (String) request.getParameter("custCode");
			String ruleId = (String) request.getParameter("ruleId") == null ? null
					: (String) request.getParameter("ruleId");

			// 设置参数
			param.put("rule_type", rule_type);
			param.put("scopeFlag", scopeFlag);
			param.put("cust_code", cust_code);
			param.put("ruleId", ruleId);
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());

			// 调用SQL,查询是否存在规则
			// 判断结果集件数
			ArrayList<HashMap<String, Object>> dbConditionList = ruleservice
					.checkRuleIsRepeat1(param);
			String returnMsg = "false";
			// 循环比较条件表数据，碰到有重复则停止查找
			if (dbConditionList.size() >= 1) {
				// 如果取出的ID 和前台得到的ID 一样 ， 则表示用户在进行修改，返回tue
				if (dbConditionList.get(0).get("RULE_ID").toString()
						.equals(ruleId)) {
					returnMsg = "true";
				} else {
					returnMsg = "false";
				}
			} else {
				returnMsg = "true";
			}
			// 反悔判断结果
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 判断规则条件之间是否有包含关系
	 * 
	 * @return True:不包含 False:包含
	 */
	@RequestMapping(value = "/checkRuleIsRepeat")
	public void checkRuleIsRepeat(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			// 获取前台页面项目值
			// rule_id
			String rule_id = (String) request.getParameter("rule_id") == null ? null
					: (String) request.getParameter("rule_id"); // 范围
			// 范围
			String scopeFlag = (String) request.getParameter("scopeFlag") == null ? null
					: (String) request.getParameter("scopeFlag");
			// 客户代码
			String cust_code = (String) request.getParameter("cust_code") == null ? null
					: (String) request.getParameter("cust_code");
			// 规则类型
			String rule_type = (String) request.getParameter("rule_type") == null ? null
					: (String) request.getParameter("rule_type");
			// 条件
			String condition_combo = (String) request
					.getParameter("condition_combo") == null ? null
					: (String) request.getParameter("condition_combo");
			// 返回值
			String returnMsg = "false";
			// 设置参数
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			param.put("scopeFlag", scopeFlag);
			param.put("cust_code", cust_code);
			param.put("rule_type", rule_type);
			// 查rule_main表，如有重复，得到rule_id，没有得到rule_id进行第二次查询
			ArrayList<HashMap<String, Object>> list = ruleservice
					.checkRuleIsRepeat1(param);
			// 循环比较条件表数据，碰到有重复的则停止查找
			if (list.size() > 0) {
				for (HashMap<String, Object> rule : list) {
					// 取得数据库里条件数据
					ArrayList<HashMap<String, Object>> dbConditionList = ruleservice
							.checkRuleIsRepeat2(rule);
					// 取得前台条件数据
					ArrayList<HashMap<String, Object>> pageConditionList = new ArrayList<HashMap<String, Object>>();
					// 进行比较
					if (condition_combo != null) {// 如果不为空
						// 分割成数组
						String[] tmp = condition_combo.split("~~");
						// 将前台条件字符串放入ArrayList
						for (int i = 0; i < tmp.length; i++) {
							HashMap<String, Object> map = new HashMap<String, Object>();
							if (!(tmp[i] == null || "".equals(tmp[i]))) {
								map.put("CONDITION_COLUMN", tmp[i]);
								pageConditionList.add(map);
							}
						}
						// 如果条件，则停止比较，返回false
						if ((dbConditionList.isEmpty() || pageConditionList
								.isEmpty())
								&& !rule.get("RULE_ID").toString()
										.equals(rule_id)) {
							returnMsg = "false";
							break;
						}
						// 如果条件有包含关系，返回False
						if ((dbConditionList.containsAll(pageConditionList) || pageConditionList
								.containsAll(dbConditionList))
								&& !rule.get("RULE_ID").toString()
										.equals(rule_id)) {
							returnMsg = "false";
							break;
						} else {
							returnMsg = "true"; // 当前客户还没有同类型规则
						}
					}
				}
			} else {
				returnMsg = "true";// 当前客户还没有同类型规则
			}
			// 　返回判断结果
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 判断当前客户是否存在
	 * 
	 * @return: True:存在；False：不存在
	 */
	@RequestMapping(value = "/checkCustCode")
	public void checkCustCode(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(companyId));
		try {
			// 获得页面客户代码
			String custCode = (String) request.getParameter("custCode") == null ? null
					: (String) request.getParameter("custCode");
			String returnMsg = "false";
			// 查询当前客户数据
			param.put("custCode", custCode);
			param.put("groupId", groupId);
			if (ruleservice.checkCustCode(param) > 0) {
				returnMsg = "true";
			}

			// 返回判定结果
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
 
	/*
	 * 获取创建者信息
	 */
	@RequestMapping(value = "/getCreator")
	public void getCreator(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		try {
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			param.put("companyId",companyId);
			param.put("language", language);
			result = ruleservice.getCreator(param);
			String returnMsg = JackJson.fromObjectToJson(result);

			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取客户信息
	 */
	@RequestMapping(value = "/getCustInfo")
	public void getCustInfo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {

		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(companyId));
		try {
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			param.put("companyId",companyId); 
			param.put("language", language);
			param.put("groupId", groupId);
			result = ruleservice.getCustInfo(param);
			String returnMsg = JackJson.fromObjectToJson(result);

			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取共通条件
	 */
	@RequestMapping(value = "/getCommonConditions")
	public void getCommonConditions(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String language=(String) session.getAttribute(WebConstants.CURRENT_LANG);
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			param.put("language", language);
			result = ruleservice.getCommonConditions(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取自定义摘要规则条件
	 */
	@RequestMapping(value = "/getCondition")
	public void getCondition(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String language=(String) session.getAttribute(WebConstants.CURRENT_LANG);
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			// 写定条件数据在后台
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			map1.put("value", "01");
			map1.put("condition", "=");
			result.add(map1);
			HashMap<String, Object> map2 = new HashMap<String, Object>();
			map2.put("value", "02");
			map2.put("condition", ">");
			result.add(map2);
			HashMap<String, Object> map3 = new HashMap<String, Object>();
			map3.put("value", "03");
			map3.put("condition", "<");
			result.add(map3);
			HashMap<String, Object> map4 = new HashMap<String, Object>();
			map4.put("value", "04");
			if(language.equals("en")){
				map4.put("condition", "Contain");
			}
			else{
				map4.put("condition", "包含");
			}
			result.add(map4);
			HashMap<String, Object> map5 = new HashMap<String, Object>();
			map5.put("value", "05");
			if(language.equals("en")){
				map5.put("condition", "Begin with");
			}
			else{
				map5.put("condition", "开头是");
			}
			result.add(map5);
			HashMap<String, Object> map6 = new HashMap<String, Object>();
			map6.put("value", "06");
			if(language.equals("en")){
				map6.put("condition", "End with");
			}
			else{
				map6.put("condition", "结尾是");
			}
			result.add(map6);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获取Fixed_Type
	 */
	@RequestMapping(value = "/getFixed_Type")
	public void getFixed_Type(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		String language=(String) session.getAttribute(WebConstants.CURRENT_LANG);
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			// 此处把 数据写定在后台
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			map1.put("value", "0");
			if(language.equals("en")){
				map1.put("fixed_Type", "front");
			}
			else {
				map1.put("fixed_Type", "前");
			}
			result.add(map1);
			HashMap<String, Object> map2 = new HashMap<String, Object>();
			map2.put("value", "1");
			if(language.equals("en")){
				map2.put("fixed_Type", "behind");
			}
			else{
				map2.put("fixed_Type", "后");
			}
			result.add(map2);

			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 修改页面---获取相应规则ＩＤ的条件
	 */
	@RequestMapping(value = "/getRuleConditions", method = RequestMethod.POST)
	public void getRuleConditions(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");
			param.put("rule_id", ruleId);

			ArrayList<String> list = new ArrayList<String>();

			ArrayList<HashMap<String, Object>> ruleConditions = ruleservice
					.getRuleConditions(param);
			for (int i = 0; i < ruleConditions.size(); i++) {
				HashMap<String, Object> ruleCon = ruleConditions.get(i);
				String condition_column = (String) ruleCon
						.get("condition_column");
				String condition = (String) ruleCon.get("condition");
				String value = (String) ruleCon.get("value");
				list.add(condition_column);
				list.add(condition);
				list.add(value);
			}

			String returnMsg = JackJson.fromObjectToJson(list);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 修改页面---获取当前ruleId的自定义摘要信息
	 */
	@RequestMapping(value = "/getAbstractInfo", method = RequestMethod.POST)
	public void getAbstractInfo(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");

			param.put("rule_id", ruleId);

			ArrayList<String> list = new ArrayList<String>();

			ArrayList<HashMap<String, Object>> abstractInfo = ruleservice
					.getAbstractInfo(param);
			for (int i = 0; i < abstractInfo.size(); i++) {
				HashMap<String, Object> absInfo = abstractInfo.get(i);
				String cusCol = absInfo.get("cus_column").toString();
				String cusType = absInfo.get("cus_type").toString();
				String fixedType = absInfo.get("fixed_type").toString();
				String fixedLen = absInfo.get("fixed_len").toString();
				String beforeFixChar = absInfo.get("before_fixed_char").toString();
				String beforeAfterType = absInfo.get("before_after_type").toString();
				String fixedText = absInfo.get("fixd_text").toString();
				list.add(cusCol);
				list.add(cusType);
				list.add(fixedType);
				list.add(fixedLen);
				list.add(beforeFixChar);
				list.add(beforeAfterType);
				list.add(fixedText);
			}
			String returnMsg = JackJson.fromObjectToJson(list);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 获得替换值
	 */
	@RequestMapping(value = "/getReplaceRule", method = RequestMethod.POST)
	public void getReplaceRule(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");

			param.put("rule_id", ruleId);
			ArrayList<HashMap<String, Object>> replaceInfo = ruleservice
					.getReplaceRule(param);
			String returnMsg = JackJson.fromObjectToJson(replaceInfo);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 替换单位
	 */
	@RequestMapping(value = "/getReplaceUnit", method = RequestMethod.POST)
	public void getReplaceUnit(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");

			param.put("rule_id", ruleId);
			ArrayList<HashMap<String, Object>> replaceUnit = ruleservice
					.getReplaceUnit(param);
			String returnMsg = JackJson.fromObjectToJson(replaceUnit);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 获取已选择的规则
	 */
	@RequestMapping(value = "/getCheckedRule")
	public void getCheckedRule(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
		try {
			Object currentCompany = session
					.getAttribute(WebConstants.CURRENT_COMPANY);
			utilMapper.getGroupIdFromCompanyId(Integer.parseInt(currentCompany
					.toString()));
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			param.put("companyId",
					session.getAttribute(WebConstants.CURRENT_COMPANY)
							.toString());
			param.put("language", language);
			// 加入查询全部规则的map
			HashMap<String, Object> all = new HashMap<String, Object>();
			if("en".equals(language)){
				all.put("type", "All Rules");
				all.put("value", "00");
			} else{
				all.put("type", "全部");
				all.put("value", "00");
			}
			result.add(all);
			result.addAll(ruleservice.getCheckedRule(param));
			// 遍历 result,将所有显示值改为规则名
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 规则删除
	 */
	@RequestMapping(value = "/deleteRuleList", method = RequestMethod.POST)
	@ResponseBody
	public Object deleteRuleList(@RequestParam String id, HttpSession session,
			HttpServletRequest request) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		int deleteRuleId = Integer.parseInt(request.getParameter("deleteRuleId"));
		String ruleType = request.getParameter("deleteRuleType");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user == null) {
				return new ExtReturn(false, "未登陆!");
			} else {
				int action = 0;
				boolean flag = this.addRuleHistory(deleteRuleId, ruleType,
						user, action);
				if (flag) {
					session.getAttribute(WebConstants.CURRENT_COMPANY);
					String[] rulelistid = id.split(",");

					List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
					for (int i = 0; i < rulelistid.length; i++) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("id", rulelistid[i]);
						list.add(map);
					}
					param.put("id", list);
					try {
						ruleservice.deleteRuleList(param);
					} catch (Exception e) {
						logger.error("Exception: ", e);
						return new ExtReturn(false, "该规则删除失败!");
					}
				}
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		}
		return new ExtReturn(true, "success");
	}

	/*
	 * 规则一览的删除
	 */
	@RequestMapping(value = "/deleteRuleList1", method = RequestMethod.POST)
	@ResponseBody
	public Object deleteRuleList1(@RequestParam String id, String rule_type,
			HttpSession session, HttpServletRequest request) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		session.getAttribute(WebConstants.CURRENT_COMPANY);

		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user == null) {
				return new ExtReturn(false, "未登陆!");
			} else {
				String[] rulelistid = id.split(",");

				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				for (int i = 0; i < rulelistid.length; i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("id", rulelistid[i]);
					list.add(map);
				}
				param.put("id", list);
				boolean flag = false;
				String[] ruleType = rule_type.split(",");
				for (int i = 0; i < ruleType.length; i++) {
					flag = this.addRuleHistory(Integer.parseInt(rulelistid[i]),
							ruleType[i], user, 0);
				}
				if (flag) {
					try {
						ruleservice.deleteRuleList(param);
					} catch (Exception e) {
						logger.error("Exception: ", e);
						return new ExtReturn(false, "该规则删除失败!");
					}
				}
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		}
		return new ExtReturn(true, "success");
	}

	/*
	 * 规则一览的查询
	 */
	@RequestMapping(value = "GetRuleList")
	public void getRuleList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) throws UnsupportedEncodingException {

		response.setContentType("text/plain;charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		try {
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			// 规则类型,如果为空，则赋值 00
			String type = (String) request.getParameter("type") == null ? "00"
					: (String) request.getParameter("type");
			// 客户名称参数
			String cust_name_chn = (String) request
					.getParameter("cust_name_chn") == null ? ""
					: (String) request.getParameter("cust_name_chn");
			// 客户代码
			String cust_code = (String) request.getParameter("cust_code") == null ? ""
					: (String) request.getParameter("cust_code");
			// 创建者参数
			String creator = (String) request.getParameter("creator") == null ? ""
					: (String) request.getParameter("creator");

			HashMap<String, Object> result = new HashMap<String, Object>();// 用于返回的结果集
			Object currentCompany = session
					.getAttribute(WebConstants.CURRENT_COMPANY);
			if (currentCompany == null) {
				return;
			}

			int pageStart = page.getStart();
			int pageEnd = page.getStart() + page.getLimit();
			String companyId=session.getAttribute(WebConstants.CURRENT_COMPANY)
					.toString();
			int groupId = utilMapper.getGroupIdFromCompanyId(Integer.parseInt(companyId));
			// 排序参数
			String orderby = "rule_id";
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("companyId",companyId);
			param.put("groupId",groupId);
			param.put("language", language);
			param.put("pageStart", pageStart);
			param.put("pageEnd", pageEnd);
			param.put("orderBy", orderby);
			param.put("type", type);
			// 客户代码
			if (cust_code.length() >= 1) {
				cust_code = "%" + cust_code + "%";
				param.put("cust_code", cust_code);
			}
			// 客户名称参数
			if (cust_name_chn.length() >= 1) {
				cust_name_chn = "%" + cust_name_chn + "%";
				param.put("cust_name_chn", cust_name_chn);
			}
			// 创建者参数
			if (creator.length() >= 1) {
				creator = "%" + creator + "%";
				param.put("creator", creator);
			}
			// 调用service
			ArrayList<HashMap<String, Object>> list = ruleservice
					.getRuleList(param);

			if (list != null && list.size() > 0) {// 准备前台所需的各种数据
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", list);
				// 改变前台显示
				changeScopeFlagName(list,language);
			} else {
				result.put("success", true);
				result.put("total", param.get("pageCount"));
				result.put("data", "");
			}
			logger.debug("{}", JackJson.fromObjectToJson(result));
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 改变有效范围数据的前台显示
	 */
	private void changeScopeFlagName(ArrayList<HashMap<String, Object>> list,String language) {
		for (HashMap<String, Object> hashMap : list) {
			for (String str : hashMap.keySet()) {
				if ("scope_flag".equals(str) && "0".equals(hashMap.get(str))) {
					if(!(language.equals("en"))){
					 hashMap.put("scope_flag", "该规则对当前客户有效");
					}else if(language.equals("en")){
					 hashMap.put("scope_flag", "Work on current customer");
					}
				}
				if ("scope_flag".equals(str) && "1".equals(hashMap.get(str))) {
					if(!(language.equals("en"))){
					hashMap.put("scope_flag", "该规则对全部客户有效");
					}else if(language.equals("en")){
						hashMap.put("scope_flag", "Work on all customers");
					}
				}
				if ("scope_flag".equals(str) && "2".equals(hashMap.get(str))) {
					if(!(language.equals("en"))){
					hashMap.put("scope_flag", "当前客户不启用该规则");
					}else if(language.equals("en")){
						hashMap.put("scope_flag", "Not work on current customer");
					}
				}
			}
		}
	}

	/*
	 * 获取规则后处理区域的值
	 */
	@RequestMapping(value = "/getAdjustAfterRule", method = RequestMethod.POST)
	public void getAdjustAfterRule(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("ruleId");
			// 放入id,进行查询
			param.put("ruleId", ruleId);
			// 返回json
			String returnMsg = JackJson.fromObjectToJson(ruleservice
					.getAdjustAfterRule(param));
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 获得返利规则
	 */
	@RequestMapping(value = "/getRebate", method = RequestMethod.POST)
	public void getRebate(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");
			// 放入id,进行查询
			param.put("ruleId", ruleId);
			// 返回json
			String returnMsg = JackJson.fromObjectToJson(ruleservice
					.getRebate(param));
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 获得折扣规则
	 */
	@RequestMapping(value = "/getDiscoun", method = RequestMethod.POST)
	public void getDiscoun(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");
			// 放入id,进行查询
			param.put("ruleId", ruleId);
			// 返回json
			String returnMsg = JackJson.fromObjectToJson(ruleservice
					.getDiscoun(param));
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 修改页面---获取当前ruleId的拆分方式
	 */
	@RequestMapping(value = "/getSplitWay", method = RequestMethod.POST)
	public void getSplitWay(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");

			param.put("rule_id", ruleId);

			HashMap<String, Object> getsplitway = ruleservice
					.getSplitWay(param);

			String returnMsg = JackJson.fromObjectToJson(getsplitway);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}

	/*
	 * 进行规则设置
	 */
	@RequestMapping(value = "/ruleSet")
	public void ruleSet(HttpSession session, HttpServletRequest request,
			PrintWriter writer) {
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		if (user == null) {
			return;
		}
		// 插入规则选定的履历
		int ruleId = -1;
		String ruleType = "0";
		int action = 1;
		boolean flag = this.addRuleHistory(ruleId, ruleType, user, action);
		if (flag) {
			HashMap<String, Object> param = new HashMap<String, Object>();
			HashMap<String, Object> result = new HashMap<String, Object>();
			// 获得company_id
			String company_id = session.getAttribute(
					WebConstants.CURRENT_COMPANY).toString();
			Date date = new Date();
			// 得到当前时间
			java.text.DateFormat format = new java.text.SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			String time = format.format(date);
			String UserId = user.getUserId();
			// 获取用户规则选中状态,1为选中，0为未选中
			String rule1 = request.getParameter("rule1");
			String rule2 = request.getParameter("rule2");
			String rule3 = request.getParameter("rule3");
			String rule4 = request.getParameter("rule4");
			String rule5 = request.getParameter("rule5");
			String rule6 = request.getParameter("rule6");
			String rule7 = request.getParameter("rule7");
			String rule8 = request.getParameter("rule8");
			String rule9 = request.getParameter("rule9");
			String rule10 = request.getParameter("rule10");
			String rule11 = request.getParameter("rule11");
			String rule12 = request.getParameter("rule12");
			String rule13 = request.getParameter("rule13");

			String rule1CN = WebConstants.RULE1_CN;
			String rule2CN = WebConstants.RULE2_CN;
			String rule3CN = WebConstants.RULE3_CN;
			String rule4CN = WebConstants.RULE4_CN;
			String rule5CN = WebConstants.RULE5_CN;
			String rule6CN = WebConstants.RULE6_CN;
			String rule7CN = WebConstants.RULE7_CN;
			String rule8CN = WebConstants.RULE8_CN;
			String rule9CN = WebConstants.RULE9_CN;
			String rule10CN = WebConstants.RULE10_CN;
			String rule11CN = WebConstants.RULE11_CN;
			String rule12CN = WebConstants.RULE12_CN;
			String rule13CN = WebConstants.RULE13_CN;
			
			String rule1EN = WebConstants.RULE1_EN;
			String rule2EN = WebConstants.RULE2_EN;
			String rule3EN = WebConstants.RULE3_EN;
			String rule4EN = WebConstants.RULE4_EN;
			String rule5EN = WebConstants.RULE5_EN;
			String rule6EN = WebConstants.RULE6_EN;
			String rule7EN = WebConstants.RULE7_EN;
			String rule8EN = WebConstants.RULE8_EN;
			String rule9EN = WebConstants.RULE9_EN;
			String rule10EN = WebConstants.RULE10_EN;
			String rule11EN = WebConstants.RULE11_EN;
			String rule12EN = WebConstants.RULE12_EN;
			String rule13EN = WebConstants.RULE13_EN;
			String[] rule = { rule1, rule2, rule3, rule4, rule5, rule6, rule7,
					rule8, rule9, rule10, rule11, rule12, rule13 };
			String[] ruletype = { "11", "12", "13", "14", "15", "16", "21",
					"22", "23", "24", "31", "32", "33" };
			String[] ruletypeCN = { rule1CN, rule2CN, rule3CN, rule4CN,
					rule5CN, rule6CN, rule7CN, rule8CN, rule9CN, rule10CN,
					rule11CN, rule12CN, rule13CN, };
			String[] ruletypeEN = { rule1EN, rule2EN, rule3EN, rule4EN,
					rule5EN, rule6EN, rule7EN, rule8EN, rule9EN, rule10EN,
					rule11EN, rule12EN, rule13EN, };
			List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < 13; i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("company_id", company_id);
				map.put("ruletype", ruletype[i]);
				map.put("rulename", ruletypeCN[i]);
				map.put("rulename_en", ruletypeEN[i]);
				map.put("rule", rule[i]);
				map.put("update_id", UserId);
				map.put("update_time", time);
 				list.add(map);
			}
			param.put("rule", list);
			param.put("company_id", company_id);
			int ret;

			// 规则状态判断
			ret = ruleservice.RuleSet(param);

			if (ret == 14) {
				result.put("resultcode", 1);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		}
	}

	/*
	 * 设置规则执行顺序
	 */
	@RequestMapping(value = "/ruleSortSet")
	public void ruleSortSet(HttpSession session, HttpServletRequest request,
			PrintWriter writer) {
		try {
			// 查找用户是否登录
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user == null) {
				return;
			}
			// 插入规则选择的履历
			int ruleId = -1;
			String ruleType = "0";
			int action = 1;
			boolean flag = this.addRuleHistory(ruleId, ruleType, user, action);
			if (flag) {
				HashMap<String, Object> param = new HashMap<String, Object>();
				HashMap<String, Object> result = new HashMap<String, Object>();
				// 获得company_id
				String company_id = session.getAttribute(
						WebConstants.CURRENT_COMPANY).toString();
				// 获得前台传过来的规则，并按顺序放进数组
				String order_combo = request.getParameter("order_combo");
				String[] order = order_combo.split("&");
				// 放入company_id
				param.put("company_id", company_id);

				int ret = 0;
				// 清空原有SORT
				ruleservice.clearSort(param);
				// 循环执行修改SORT
				for (int i = 0; i < order.length; i++) {
					param.put("SORT", i + 1);
					param.put("RULE_TYPE", order[i]);
					ret = ruleservice.updateSort(param);
					// 更改失败
					if (ret != 1) {
						result.put("resultcode", 9);
						writer.print(JackJson.fromObjectToJson(result));
						return;
					}
				}
				// 成功后告诉前台
				result.put("resultcode", 1);
				writer.print(JackJson.fromObjectToJson(result));
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 取得规则执行顺序 用于顺序设置页面下拉框的赋值
	 */
	@RequestMapping(value = "/getRuleSort")
	public void getRuleSort(HttpSession session, HttpServletRequest request,
			PrintWriter writer) {
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user == null) {
				return;
			}
			HashMap<String, Object> param = new HashMap<String, Object>();
			ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
			String company_id = session.getAttribute(
					WebConstants.CURRENT_COMPANY).toString();
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			param.put("company_id", company_id);
			param.put("language", language);
			ArrayList<HashMap<String, Object>> logs = ruleservice
					.getRuleSort(param);

			result.addAll(logs);
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 添加规则履历
	 * @param urleId 已添加的规则ID，根据此参数查询出要删除的数据
	 * @param user 当前用户，用来添加执行操作的用户id
	 * @param action 0为删除，1为修改
	 * @return
	 */
	private boolean addRuleHistory(int ruleId, String ruleType, User user,
			int action) {
		try {
			HashMap<String, Object> history_param = new HashMap<String, Object>();
			history_param.put("ruleId", ruleId);
			history_param.put("ruleType", ruleType);
			history_param.put("action", action);
			history_param.put("user_id", user.getUserId());
			history_param.put("user_name", user.getAccount());
			ruleservice.addRuleHistory(history_param);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/*
	 * 修改页面---获取单据状态的值
	 */
	@RequestMapping(value = "/getDocType", method = RequestMethod.POST)
	public void getDocType(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			String ruleId = request.getParameter("rule_id");
			param.put("rule_id", ruleId);

			HashMap<String, Object> returnMap=ruleservice.getDocType(param);
			String returnMsg = JackJson.fromObjectToJson(returnMap);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: {}", e);
		}
	}
	
	/**
	 * 保存规则
	 */
	@RequestMapping(value = "/saveRules", method = RequestMethod.POST)
	@ResponseBody
	public void saveRules(HttpSession session,HttpServletRequest request,PrintWriter writer) {
		
		String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
		User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		if(user != null){
			/** 
			 * 规则大类型 @ruleBigType
			 * @ruleBigType = 1 特殊规则
			 * @ruleBigType = 2 替换商品名、替换客户、替换规格
			 * @ruleBigType = 3 替换单位
			 * @ruleBigType = 4 自定义摘要、自定义备注
			 * @ruleBigType = 5 单据状态
			 */
			String ruleBigType = request.getParameter("ruleBigType");
			
			/******************************** 规则页面共同条件********************************/
			// 规则id 当其值为-1时为新建规则 为其他时为修改
			String ruleId = request.getParameter("ruleId");
			// 规则类型
			String ruleType = request.getParameter("ruleType");
			// 规则范围
			String scopeFlag = (String) request.getParameter("scopeFlag");
			// 客户代码
			String custCode = (String) request.getParameter("custCode");
			// 备注
			String m_remark = (String) request.getParameter("m_remark");
			// 规则执行条件 
			String condition = (String) request.getParameter("condition");
			/******************************** 规则页面共同条件  end ********************************/
			/**折扣----------------------*/
			// 折扣上限
			String discountLimit = (String) request.getParameter("discountLimit");
			/**返利----------------------*/
			// 返利金额重置flag
			String rebateReset = request.getParameter("rebateReset");
			// 返利总额
			String rebateLimit = request.getParameter("rebateLimit");
			// 计价方式（含税，不含税）
			String rebatePriceWay = request.getParameter("rebatePriceWay");
			// 返利总额
			String rebateBalance = request.getParameter("rebateBalance");
			// 返利开始日期
			String rebateSdate = request.getParameter("rebateSdate");
			// 返利结束日期
			String rebateEdate = request.getParameter("rebateEdate");
			// 返利率
			String rebateRate = request.getParameter("rebateRate");
			/**拆分----------------------*/
			// 拆分方式 0 为最大金额拆分 1 为固定比率拆分
			String splitWay = request.getParameter("splitWay");
			// 拆分最大金额
			String splitMountOrRatio = request.getParameter("splitMountOrRatio");
			/******************************** 后处理  *********************************/
			// 特殊规则的转换后处理条件下拉框中的值
			String amountCom = request.getParameter("amount");
			String priceCom = request.getParameter("price");
			String tradeNameCom = request.getParameter("tradeName");
			String specificationCom = request.getParameter("specification");
			String unitCom = request.getParameter("unit");
			String remarkCom = request.getParameter("remark");
			String summaryCom = request.getParameter("summary");
			String discountRateCom = request.getParameter("discountRate");
			/******************************** 后处理  end  *********************************/
			
			/** 替换规则*/
			// 替换商品名
			String goodsName = request.getParameter("goodsName");
			
			// 替换客户
			String customers = request.getParameter("customers");
			
			// 替换单位
			// 替换前单位
			String unitBefore = request.getParameter("unitBefore");
			// 替换后单位
			String unitAfter = request.getParameter("unitAfter");
			// 替换率
			String replaceRate = request.getParameter("replaceRate");
			
			// 替换规格
			String type = request.getParameter("type");
			
			/** 自定义规则*/
			// 自定义摘要
			String defineAbstract = request.getParameter("defineAbstract");
			// 自定义备注
			String defineRemarks = request.getParameter("defineRemarks");
			// 单据状态
			String docStatus = request.getParameter("docStatus");
			// 单据状态
			String docKeep = request.getParameter("docKeep");
			/**取值结束****************************************************************/
			
			/** 处理值 ****************************************************************/
			// 规则执行条件数据处理
			String[] conditionTemp = null;
			
			if (!(condition == "")) {
				if (condition.contains("&")) {
					conditionTemp = condition.split("~~");
					List<HashMap<String, String>> conditionList = new ArrayList<HashMap<String, String>>();
					for (int i = 0; i < conditionTemp.length; i++) {
						String[] conditionTemp_t = conditionTemp[i].split("&");
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("conditionColumn", conditionTemp_t[0]);
						map.put("condition", conditionTemp_t[1]);
						map.put("conditionValue", conditionTemp_t[2]);
						conditionList.add(map);
					}
					if (!(conditionList.size() == 0)) {
						param.put("condition", conditionList);
					}
				} else {
					List<HashMap<String, String>> conditionList = new ArrayList<HashMap<String, String>>();
					conditionTemp = condition.split("~~");
					for (int i = 0; i < conditionTemp.length; i++) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("conditionColumn", conditionTemp[i]);
						map.put("condition", "10");
						conditionList.add(map);
					}
					if (!(conditionList.size() == 0)) {
						param.put("condition", conditionList);
					}
				}
			}
			
			if(ruleBigType.equals("1")){
				// 特殊规则后处理数据处理
				String[] adjustString = { amountCom, priceCom, tradeNameCom, specificationCom, 
						unitCom,remarkCom, summaryCom, discountRateCom };
				List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
				for (int i = 0; i < adjustString.length; i++) {
					if (!(adjustString[i] == null)) {
						String[] strs = adjustString[i].split("&");
						if (strs.length == 2 && !"00".equals(strs[1])) {
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("adjust_column", strs[0]);
							map.put("adjust_type", strs[1]);
							map.put("fixed_text", null);
							list.add(map);
						} else if (strs.length == 3) {
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("adjust_column", strs[0]);
							map.put("adjust_type", strs[1]);
							map.put("fixed_text", strs[2]);
							list.add(map);
						}
					}
				}
				if (list.size() == 0) {
					param.put("adjustString", null);
				} else {
					param.put("adjustString", list);
				}
			}
			if (!scopeFlag.equals("2")) {
				// 拆分规则>-拆分方式
				if (ruleType.equals("14")) {
					param.put("splitWay", splitWay);
					if (splitWay.equals("0")) {
						param.put("splitMountOrRatio", splitMountOrRatio);
					} else {
						String[] splitMountOrRatioList = splitMountOrRatio.split("&");
						param.put("split_rate_1", splitMountOrRatioList[0]);
						param.put("split_rate_2", splitMountOrRatioList[1]);
						param.put("split_rate_3", splitMountOrRatioList[2]);
						param.put("split_rate_4", splitMountOrRatioList[3]);
						param.put("split_rate_5", splitMountOrRatioList[4]);
					}
				}
				// 自定义摘要
				if (ruleType.equals("31")) {
					List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
					String defineAbstractList[] = defineAbstract.split("&", -1);
					// 自定义摘要和备注表信息
					for (int i = 0; i < defineAbstractList.length - 1;) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("cus_column", defineAbstractList[i]);
						map.put("cus_type", defineAbstractList[i + 1]);
						map.put("fixed_type", defineAbstractList[i + 2]);
						map.put("fixed_len", defineAbstractList[i + 3]);
						map.put("before_fixed_char", defineAbstractList[i + 4]);
						map.put("before_after_type", defineAbstractList[i + 5]);
						map.put("fixed_text", defineAbstractList[i + 6]);
						i = i + 7;
						list.add(map);
					}
					param.put("defineAbstract", list);
				}
				// 自定义备注
				else if (ruleType.equals("32")){
					List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
					String defineRemarksList[] = defineRemarks.split("&", -1);
					// 自定义摘要和备注表信息
					for (int i = 0; i < defineRemarksList.length - 1;) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("cus_column", defineRemarksList[i]);
						map.put("cus_type", defineRemarksList[i + 1]);
						map.put("fixed_type", defineRemarksList[i + 2]);
						map.put("fixed_len", defineRemarksList[i + 3]);
						map.put("before_fixed_char", defineRemarksList[i + 4]);
						map.put("before_after_type", defineRemarksList[i + 5]);
						map.put("fixed_text", defineRemarksList[i + 6]);
						i = i + 7;
						list.add(map);
					}
					param.put("defineRemark", list);
				}
			}
			
			/** 处理结束 ****************************************************************/
			
			param.put("ruleBigType", ruleBigType);
			param.put("ruleType", ruleType);
			param.put("scopeFlag", scopeFlag);
			param.put("custCode", custCode);
			param.put("m_remark", m_remark);
			
			// 折扣
			if (ruleType.equals("12")) {
				param.put("discountLimit", discountLimit);
			}
			// 返利
			else if (ruleType.equals("13")) {
				param.put("rebateReset", rebateReset);
				param.put("rebateLimit", rebateLimit);
				param.put("rebatePriceWay", rebatePriceWay);
				param.put("rebateBalance", rebateBalance);
				param.put("rebateSdate", rebateSdate);
				param.put("rebateEdate", rebateEdate);
				param.put("rebateRate", rebateRate);
			}
			// 替换商品名
			else if (ruleType.equals("21")) {
				param.put("goodsName", goodsName);
			}
			// 替换客户
			else if (ruleType.equals("22")) {
				param.put("customers", customers);
			}
			// 替换单位
			else if (ruleType.equals("23")) {
				param.put("unitBefore", unitBefore);
				param.put("unitAfter", unitAfter);
				param.put("replaceRate", replaceRate);
			}
			// 替换规格
			else if (ruleType.equals("24")) {
				param.put("type", type);
			}
			// 单据状态
			else if (ruleType.equals("33")) {
				param.put("docStatus", docStatus);
				if (docKeep.equals("true")) {
					param.put("docKeep", 1);
				} else {
					param.put("docKeep", 0);
				}
			}
			
			param.put("companyId", companyId);
			param.put("userId", user.getUserId());
			
			int ret = -1;
			if (ruleId.equals("-1")){
				// 保存操作
				try {
					ret = ruleservice.insertRules(param);
					result.put("resultcode", ret);
					writer.print(JackJson.fromObjectToJson(result));
				} catch (Exception e) {
					logger.error("Exception: ", e);
					result.put("resultcode", ret);
					writer.print(JackJson.fromObjectToJson(result));
				}
			} else {
				// 履历添加
				boolean flag = false;
				flag = this.addRuleHistory(Integer.parseInt(ruleId),ruleType, user, 1);
				if (flag) {
					// 修改操作
					try {
						param.put("ruleId", ruleId);
						ret = ruleservice.updateRules(param);
						result.put("resultcode", ret);
						writer.print(JackJson.fromObjectToJson(result));
					} catch (Exception e) {
						logger.error("Exception: ", e);
						result.put("resultcode", ret);
						writer.print(JackJson.fromObjectToJson(result));
					}
				}
			}
		}
	}
	
	@RequestMapping(value = "/getLockStatus")
	public void getLockStatus(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		
		try {
			int companyId = Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			param.put("companyId", companyId);
			
			int lockStatus = ruleservice.getLockStatus(param);
			result.put("resultCode", lockStatus);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
}